package com.hrt.common.safe;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 定义登录锁定问题
 *
 */
public class LoginLock {

	// 次数
	public static Map<String, List<Date>> logins = new HashMap<String, List<Date>>();
	// 登录锁定时间
	public static Map<String, Date> loginLocks = new HashMap<String, Date>();

	// 锁定1小时
	private static final int stLockHour =1;
	// 5分钟内失败多少次锁定帐号
	private static final int stLoginMinute = 5;
	// 5分钟内失败5次锁定帐号
	private static final int stLoginTimes = 5;

	/**
	 * 查看当前是否可以登录
	 * @param user
	 * @return
	 */
	public static boolean getCanLogin(String user){

		if(loginLocks.containsKey(user)){
			Date lockDate = loginLocks.get(user);
			// 相差的小时
			long lockTime = getDiffDayEx2(lockDate);
			if(lockTime>=stLockHour){
				loginLocks.remove(user);
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
	}

	/**
	 * 登录失败，记录登录失败
	 * @param user
	 * @return 返回失败的次数
	 */
	public static int setLogin(String user){

		List<Date> loginTimes = null;

		if(logins.containsKey(user)){
			loginTimes = logins.get(user);
		}else{
			loginTimes = new ArrayList<Date>();
			logins.put(user, loginTimes);
		}

		loginTimes.add(new Date());

		// 5分钟以内，登录失败，就锁定帐号
		int i = loginTimes.size() - 1;
		int count = 0;
		for(;i>=0;i--){
			Date lockDate = loginTimes.get(i);
			long lockFz = getDiffDayEx3(lockDate);
			// 大于5分钟，去掉锁定时间
			if(lockFz>stLoginMinute){
				loginTimes.remove(i);
			}else{
				count ++ ;
			}
		}

		// 大于5次锁定
		if(count>=stLoginTimes){
			loginLocks.put(user, new Date());
		}
		return count;
	}


	public static long getDiffDayEx2(Date date){
		try {
			long DAY = 10L * 60L * 1000L;//??????????  (????*??*????)
			return (( new Date().getTime() - date.getTime() ) / DAY );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1L;
	}


	public static long getDiffDayEx3(Date date){
		try {
			long DAY = 60L * 1000L;
			return (( new Date().getTime() - date.getTime() ) / DAY );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0L;
	}
}
